package com.xl.base.service;

import java.util.List;
import java.util.UUID;

import com.xl.base.annotation.DataSource;
import com.xl.base.dao.BaseDao;
import com.xl.base.entity.BaseEntity.DELETED;
import com.xl.base.entity.Operator;
import com.xl.base.page.BasePage;
import com.xl.core.enums.SourceEnum;
import com.xl.core.util.ClassReflectUtil;
import com.xl.core.util.DateUtils;
import com.xl.core.util.SessionLocalUtils;

public abstract class BaseService<T> {

	public abstract BaseDao<T> getDao();

	public void add(T t) throws Exception {
		// 设置主键.字符类型采用UUID,数字类型采用自增
		ClassReflectUtil.setFieldValue(t, "id", UUID.randomUUID().toString());
		// 设置新建人与新建日期
		ClassReflectUtil.setFieldValue(t, "createDate", DateUtils.getDate());
		Operator operator = SessionLocalUtils.getOperator();
		if (operator != null && operator.getMember() != null) {
			ClassReflectUtil.setFieldValue(t, "createBy", operator.getMember()
					.getId());
		}
		// 设置删除标记位为正常
		ClassReflectUtil.setFieldValue(t, "delFlag", DELETED.NO.key);

		// 设置更新人与更新日期
		preUpdate(t);

		getDao().add(t);
	}

	public void update(T t) throws Exception {
		// 设置更新人与更新日期
		preUpdate(t);
		getDao().update(t);
	}

	public void updateBySelective(T t) throws Exception {
		// 设置更新人与更新日期
		preUpdate(t);
		getDao().updateBySelective(t);
	}

	public void delete(Object... ids) throws Exception {
		if (ids == null || ids.length < 1) {
			return;
		}
		for (Object id : ids) {
			getDao().delete(id);
		}
	}

	@DataSource(source = SourceEnum.TYPE_SLAVE)
	public int queryByCount(BasePage page) throws Exception {
		return getDao().queryByCount(page);
	}

	@DataSource(source = SourceEnum.TYPE_SLAVE)
	public List<T> queryByList(BasePage page) throws Exception {
		Integer rowCount = queryByCount(page);
		page.getPager().setRowCount(rowCount);
		return getDao().queryByList(page);
	}

	@DataSource(source = SourceEnum.TYPE_SLAVE)
	public T queryById(Object id) throws Exception {
		return getDao().queryById(id);
	}

	private void preUpdate(T t) throws Exception {
		// 设置更新人与更新日期
		ClassReflectUtil.setFieldValue(t, "updateDate", DateUtils.getDate());
		Operator operator = SessionLocalUtils.getOperator();
		if (operator != null && operator.getMember() != null) {
			ClassReflectUtil.setFieldValue(t, "updateBy", operator.getMember()
					.getId());
		}
	}
}
